home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 3_11.lha / 3_11 / 3_11a_b.c next >
Text File  |  1993-08-08  |  578b  |  33 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. /  Convert a string of digits into an integer,
  6. /  checking for overflow
  7. /  Version 2
  8. include <ctype.h>
  9. include <limits.h>
  10. include <error.h>
  11.  
  12. nt atoi(const char *s)
  13.  
  14.    for (int i = 0; isdigit(*s); s++)
  15.        {
  16. if (i > INT_MAX / 10)
  17.     break;
  18. i *= 10;
  19. int n = *s - '0';
  20. if (i > INT_MAX - n)
  21.     break;
  22. i += n;
  23. }
  24.  
  25.    if (isdigit(*s))
  26.        error("integer overflow");
  27.  
  28.    else if (*s)
  29.        error("malformed integer");
  30.  
  31.    return i;
  32.  
  33.